const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const nodemailer = require('nodemailer');
const crypto = require('crypto');
const { db } = require('../app');

// 邮件发送器配置
function createMailer() {
    return nodemailer.createTransporter({
        host: process.env.SMTP_HOST || 'smtp.qq.com',
        port: parseInt(process.env.SMTP_PORT) || 587,
        secure: process.env.SMTP_SECURE === 'true',
        auth: {
            user: process.env.SMTP_USER,
            pass: process.env.SMTP_PASS
        },
        tls: {
            rejectUnauthorized: false
        }
    });
}

// 注册路由
router.post('/register', async (req, res) => {
    const { username, email, password, confirm_password } = req.body;

    // 验证输入
    if (!username || !email || !password || !confirm_password) {
        return res.status(400).json({ error: '所有字段都是必需的' });
    }

    if (password !== confirm_password) {
        return res.status(400).json({ error: '密码不匹配' });
    }

    if (password.length < 6) {
        return res.status(400).json({ error: '密码长度至少为6位' });
    }

    try {
        // 检查用户名是否已存在
        db.get('SELECT id FROM users WHERE username = ?', [username], async (err, user) => {
            if (err) {
                return res.status(500).json({ error: '数据库错误' });
            }
            if (user) {
                return res.status(400).json({ error: '用户名已存在' });
            }

            // 检查邮箱是否已存在
            db.get('SELECT id FROM users WHERE email = ?', [email], async (err, user) => {
                if (err) {
                    return res.status(500).json({ error: '数据库错误' });
                }
                if (user) {
                    return res.status(400).json({ error: '邮箱已被注册' });
                }

                // 加密密码
                const hashedPassword = await bcrypt.hash(password, parseInt(process.env.BCRYPT_ROUNDS) || 12);
                
                // 生成验证令牌
                const verificationToken = crypto.randomBytes(32).toString('hex');

                // 插入用户
                db.run(
                    'INSERT INTO users (username, email, password, verification_token) VALUES (?, ?, ?, ?)',
                    [username, email, hashedPassword, verificationToken],
                    function(err) {
                        if (err) {
                            return res.status(500).json({ error: '注册失败' });
                        }

                        // 检查是否需要邮件验证
                        db.get("SELECT value FROM settings WHERE key = 'require_email_verification'", (err, setting) => {
                            const requireVerification = setting ? setting.value === 'true' : true;

                            if (requireVerification) {
                                // 发送验证邮件
                                const mailer = createMailer();
                                const verificationUrl = `${req.protocol}://${req.get('host')}/auth/verify/${verificationToken}`;

                                const mailOptions = {
                                    from: process.env.SMTP_USER,
                                    to: email,
                                    subject: 'Minecraft面板 - 邮箱验证',
                                    html: `
                                        <h2>欢迎加入Minecraft面板！</h2>
                                        <p>请点击以下链接验证您的邮箱：</p>
                                        <a href="${verificationUrl}" style="background-color: #4CAF50; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px;">验证邮箱</a>
                                        <p>如果按钮不起作用，请复制以下链接到浏览器：</p>
                                        <p>${verificationUrl}</p>
                                        <p>此链接将在24小时后过期。</p>
                                    `
                                };

                                mailer.sendMail(mailOptions, (error, info) => {
                                    if (error) {
                                        console.error('邮件发送失败:', error);
                                        return res.status(500).json({ error: '注册成功，但验证邮件发送失败' });
                                    }
                                    res.json({ success: true, message: '注册成功！请检查您的邮箱进行验证。' });
                                });
                            } else {
                                // 不需要验证，直接激活账户
                                db.run('UPDATE users SET is_verified = 1 WHERE id = ?', [this.lastID]);
                                res.json({ success: true, message: '注册成功！您现在可以登录了。' });
                            }
                        });
                    }
                );
            });
        });
    } catch (error) {
        console.error('注册错误:', error);
        res.status(500).json({ error: '服务器错误' });
    }
});

// 登录路由
router.post('/login', (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).json({ error: '用户名和密码都是必需的' });
    }

    db.get('SELECT * FROM users WHERE username = ?', [username], async (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }

        if (!user) {
            return res.status(400).json({ error: '用户名或密码错误' });
        }

        // 检查账户是否已验证
        if (!user.is_verified) {
            return res.status(400).json({ error: '账户未验证，请检查您的邮箱' });
        }

        // 验证密码
        const isValidPassword = await bcrypt.compare(password, user.password);
        if (!isValidPassword) {
            return res.status(400).json({ error: '用户名或密码错误' });
        }

        // 设置会话
        req.session.user = {
            id: user.id,
            username: user.username,
            email: user.email,
            role: user.role
        };

        res.json({ success: true, message: '登录成功', user: req.session.user });
    });
});

// 登出路由
router.post('/logout', (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            return res.status(500).json({ error: '登出失败' });
        }
        res.json({ success: true, message: '登出成功' });
    });
});

// 邮箱验证路由
router.get('/verify/:token', (req, res) => {
    const { token } = req.params;

    db.get('SELECT * FROM users WHERE verification_token = ?', [token], (err, user) => {
        if (err) {
            return res.status(500).send('验证失败');
        }

        if (!user) {
            return res.status(400).send('无效的验证链接');
        }

        if (user.is_verified) {
            return res.send('账户已经验证过了');
        }

        // 更新用户状态
        db.run(
            'UPDATE users SET is_verified = 1, verification_token = NULL WHERE id = ?',
            [user.id],
            (err) => {
                if (err) {
                    return res.status(500).send('验证失败');
                }
                res.send('邮箱验证成功！您现在可以登录了。');
            }
        );
    });
});

// 检查登录状态
router.get('/check', (req, res) => {
    if (req.session.user) {
        res.json({ logged_in: true, user: req.session.user });
    } else {
        res.json({ logged_in: false });
    }
});

// 初始化管理员账户
router.post('/init', async (req, res) => {
    const { username, email, password, panel_name, panel_ip } = req.body;

    // 验证输入
    if (!username || !email || !password || !panel_name || !panel_ip) {
        return res.status(400).json({ error: '所有字段都是必需的' });
    }

    // 检查是否已经初始化
    db.get("SELECT COUNT(*) as count FROM users", async (err, row) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (row.count > 0) {
            return res.status(400).json({ error: '系统已经初始化过了' });
        }

        try {
            // 加密密码
            const hashedPassword = await bcrypt.hash(password, parseInt(process.env.BCRYPT_ROUNDS) || 12);

            // 插入管理员用户
            db.run(
                'INSERT INTO users (username, email, password, role, is_verified) VALUES (?, ?, ?, ?, ?)',
                [username, email, hashedPassword, 'admin', 1],
                function(err) {
                    if (err) {
                        return res.status(500).json({ error: '初始化失败' });
                    }

                    // 插入系统设置
                    const settings = [
                        ['panel_name', panel_name],
                        ['panel_ip', panel_ip],
                        ['require_email_verification', 'false'],
                        ['smtp_host', process.env.SMTP_HOST || 'smtp.qq.com'],
                        ['smtp_port', process.env.SMTP_PORT || '587'],
                        ['smtp_user', process.env.SMTP_USER || ''],
                        ['smtp_secure', process.env.SMTP_SECURE || 'false'],
                        ['smtp_tls', process.env.SMTP_TLS || 'true']
                    ];

                    settings.forEach(([key, value]) => {
                        db.run('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)', [key, value]);
                    });

                    res.json({ success: true, message: '初始化成功！您现在可以登录了。' });
                }
            );
        } catch (error) {
            console.error('初始化错误:', error);
            res.status(500).json({ error: '服务器错误' });
        }
    });
});

module.exports = router;